import React, { useState, useEffect } from 'react'
import logo from '../../assets/logo.svg';
import style from './Header.module.css';
import {
  Layout, 
  Typography, 
  Input, 
  Menu, 
  Button, 
  Dropdown 
} from 'antd'
import { GlobalOutlined } from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom'
import { RootState } from '../../redux/store'
import { useSelector}  from '../../redux/hooks'
import { useDispatch } from 'react-redux';
import { useTranslation } from 'react-i18next'
import { changeLanguageActionCreator } from '../../redux/language/languageActions'
import jwt_decode, { JwtPayload as DefaultJwtPayload } from 'jwt-decode'
import { userSlice } from '../../redux/user/slice';

// 定义自己的jwt类型定义
interface JwtPayload extends DefaultJwtPayload {
  username: string | unknown
}

export const Header: React.FC = () => {
  let navigate = useNavigate();
  const language =  useSelector((state) => state.language.language)
  const languageList =  useSelector((state) => state.language.languageList)
  const dispatch = useDispatch()
  const {t, i18n} = useTranslation()
  console.log(language, 'store')


  const shoppingCartItems = useSelector(s => s.shoppingCart.items)
  const shoppingCartLoading = useSelector(s => s.shoppingCart.loading)

  
  // jwt
  const jwt = useSelector(s => s.user.token)
  const [username, setUsername] = useState<any>('')
  // 监听jwt变化
  useEffect(() => {
    if (jwt) {
      const token = jwt_decode<JwtPayload>(jwt)
      setUsername(token.username)
    }
  }, [jwt])
  
  const menuItemList = [
    {
      title: t("header.home_page"),
      key: 1
    },
    {
      title: t("header.weekend"),
      key: 2
    },
    {
      title: t("header.group"),
      key: 3
    },
    {
      title: t("header.backpack"),
      key: 4
    },
    {
      title: t("header.private"),
      key: 5
    },
    {
      title: t("header.cruise"),
      key: 6
    },
    {
      title: t("header.hotel"),
      key: 7
    },
    {
      title: t("header.local"),
      key: 8
    },
    {
      title: t("header.theme"),
      key: 9
    },
    {
      title: t("header.custom"),
      key: 10
    },
    {
      title: t("header.study"),
      key: 11
    },
    {
      title: t("header.visa"),
      key: 12
    },
    {
      title: t("header.enterprise"),
      key: 13
    },
    {
      title: t("header.high_end"),
      key: 14
    },
    {
      title: t("header.outdoor"),
      key: 15
    },
    {
      title: t("header.insurance"),
      key: 16
    }
  ]
  function itemClick(e){
    console.log(e)
    // 规范化reducer
    let action = changeLanguageActionCreator(e.name)
    i18n.changeLanguage(e.code)
    dispatch(action)
  }
  function onLogout() {
    // 登出需要清除jwt数据
    dispatch(userSlice.actions.logOut())
    navigate('/')
  }
  return <>
        <div className={style['app-header']}>
        {/* top-header */}
        <div className={style['top-header']}>
          <div className={style.inner}>
            <Typography.Text>
              {t("header.slogan")}
            </Typography.Text>
            <Dropdown.Button
              style={{marginLeft: '15px'}}
              overlay={
                <Menu>
                  {
                    languageList.map((item, index) => {
                      return (
                        <Menu.Item onClick={() => itemClick(item)} key={item.code}>{item.name}</Menu.Item>
                      )
                    })
                  }
                </Menu>
              }
              icon={<GlobalOutlined />}
            >
              {language === 'zh' ? '中文' : '英文'}
            </Dropdown.Button>
            {
              jwt ? 
              <Button.Group className={style['button-group']}>
                <span>{t("header.welcome")}</span>
                <Typography.Text>{username}</Typography.Text>
                <Button loading={shoppingCartLoading} onClick={ () => navigate('/shoppingCart') }>{t("header.shoppingCart")}({shoppingCartItems.length})</Button>
                <Button onClick={onLogout}>{t("header.signOut")}</Button>
              </Button.Group>
              :
              <Button.Group className={style['button-group']}>
                <Button onClick={() => navigate('/register')}>
                  {t("header.register")}
                </Button>
                <Button onClick={() => navigate('/signIn')}>
                  {t("header.signin")}
                </Button>
              </Button.Group>
            }
          </div>
        </div>
        <Layout.Header className={style['main-header']}>
          <span onClick={() => navigate('/')}>
            <img src={logo} alt="React17" className={style['App-logo']} />
            <Typography.Title level={3} className={style.title}>M78星云居委会</Typography.Title>
          </span>
          <Input.Search 
            className={style['search-input']} 
            placeholder="请输入跃迁导航坐标"
            onSearch={(keywords) => navigate("/search/" + keywords)}
          ></Input.Search>
        </Layout.Header>
        <Menu mode={'horizontal'} className={style['main-menu']}>
          {
            menuItemList.map(item => {
              return (
                <Menu.Item key={item.key}>{item.title}</Menu.Item>
              )
            })
          }
        </Menu>
      </div>
    </>
}
